﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Utility.Json;
using System.Text.RegularExpressions;

namespace EzDesk.Utility.EzML
{
    public static class EzMLHelper
    {
        /// <summary>
        /// 将json格式的数据合并到ezml中
        /// </summary>
        /// <param name="originalStr"></param>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public static string MergeDataToEzML(string originalStr, string jsonData)
        {
            if (String.IsNullOrEmpty(originalStr))
            {
                return originalStr;
            }

            var parameters = JsonHelper.JsonToDictionary(jsonData);

            return MergeDataToEzML(originalStr, parameters);
        }

        public static string MergeDataToEzML(string originalStr, IDictionary<string, string> parameters)
        {
            Regex regex = new Regex(
                @"(?<={)\w+(?=})",
                RegexOptions.IgnoreCase | RegexOptions.Compiled
                );

            string stringInput = originalStr;
            string result = originalStr;
            MatchCollection coll = regex.Matches(stringInput);


            foreach (Match match in coll)
            {
                string variable = match.Value as string;
                if (parameters.Keys.Contains(variable))
                {
                    result = result.Replace("{" + variable + "}", parameters[variable]);
                }
                else
                {
                    result = result.Replace("{" + variable + "}", "#undefine#");
                    
                    //TODO: 包含没有定义的变量
                    //throw new Exception("FeedData与Template合并错误！  " + match.Value + "找不到。");
                }
            }

            return result;
        }
    }
}
